package com.easylinkin.linkappapi.security.config;

import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

/**
 * @author zhengwen
 */
@Slf4j
@Component
public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {

    @Autowired
    private LinkappRestAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) {
        // 1. 获取用户名
        UserDetails userDetails =
                (UserDetails) event.getSessionInformation().getPrincipal();

        AuthenticationException exception =
                new AuthenticationServiceException(
                        String.format("[%s]用户在其他地方登录,您已被下线", userDetails.getUsername()));
        //TODO 这里可以增加根据用户名找到手机号信息，进行推送信息，或者在myAuthenticationFailureHandler里去处理
        try {
            // 当用户在其他地方登录后,交给失败处理器回到认证页面
            event.getRequest().setAttribute("toAuthentication", true);
            myAuthenticationFailureHandler
                    .onAuthenticationFailure(event.getRequest(), event.getResponse(), exception);
        } catch (Exception e) {
            log.error("--登录失效session清除异常，原因：{}", e.getMessage());
            throw new BusinessException("超时登录session清除异常");
        }
    }
}

